package vn.anhqn.englishsentensetranslator.utils;

import java.io.IOException;

import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;

public class AudioUtils implements OnCompletionListener, OnErrorListener,
		OnPreparedListener {

	public static AudioUtils INSTANCE;
	private MediaPlayer mediaPlayer;
	boolean isPlaying;
	IPlaybackListener playListener;

	public interface IPlaybackListener {
		public void onPre();

		public void onComplete();

		public void onError();

	}

	public void setPlayListener(IPlaybackListener i) {
		this.playListener = i;
	}

	public static AudioUtils getIntance() {
		if (INSTANCE == null)
			INSTANCE = new AudioUtils();
		return INSTANCE;
	}

	public void playAudioFromUrl(String url) {
		stopPlay();
		mediaPlayer = new MediaPlayer();
		mediaPlayer.setOnCompletionListener(this);
		mediaPlayer.setOnErrorListener(this);
		mediaPlayer.setOnPreparedListener(this);
		try {
			mediaPlayer.setDataSource(url);
			if (playListener != null) {
				//playListener.onPre();
				mediaPlayer.prepareAsync();
			}
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public void stopPlay() {
		if (mediaPlayer != null) {
			try {
				//mediaPlayer.stop();
				mediaPlayer.release();
				if (playListener != null)
					playListener.onComplete();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {
		if (playListener != null)
			playListener.onError();
		return false;
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		if (playListener != null)
			playListener.onComplete();
	}

	@Override
	public void onPrepared(MediaPlayer mp) {
		mp.start();
	}
}
